package com.doge.walknovel.business.novel.viewholders

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.doge.wnpro.R
import com.doge.walknovel.api.model.NovelDetailInfo
import com.doge.walknovel.business.novel.CHAPTERS
import com.doge.walknovel.business.novel.RATING
import com.doge.walknovel.core.base.adapters.AdapterCallback
import com.doge.wnpro.databinding.CellNovelInfoBinding
import com.doge.walknovel.utils.*

class NovelInfoViewHolder(
    parent: ViewGroup,
    callback: AdapterCallback,
    private val binding: CellNovelInfoBinding = CellNovelInfoBinding.inflate(
        LayoutInflater.from(parent.context), parent, false),
) : RecyclerView.ViewHolder(binding.root) {
    private val tags by lazy { arrayOf(binding.tag1, binding.tag2, binding.tag3, binding.tag4, binding.tag5, binding.tag6, binding.tag7, binding.tag8, binding.tag9) }

    init {
        binding.chapters.setOnClickCallback {
            callback.invoke(CHAPTERS, itemView.tag)
        }
        binding.viewRating.setOnClickCallback {
            if ((itemView.tag as? NovelDetailInfo?)?.scoreFlag != 1) {
                callback.invoke(RATING, itemView.tag)
            }
        }
        binding.descExpand.setOnClickListener {
            if (binding.desc.maxLines != Int.MAX_VALUE) {
                binding.desc.maxLines = Int.MAX_VALUE
                binding.descExpand.rotation = 180f
            } else {
                binding.desc.maxLines = 5
                binding.descExpand.rotation = 0f
            }
        }

    }

    fun bind(item: NovelDetailInfo) {
        itemView.tag = item

        binding.cover.load(
            item.coverUrl,
            R.drawable.shape_f7f7f7_4,
            transformation = RoundedCorners4,
            width = 76.dp,
            height = 108.dp
        )
        binding.bookName.text = item.title
        binding.author.text = item.author
        binding.language.text = item.language
        binding.score.text = item.score.toString()
        binding.scoreStar.setScore(item.score ?: 0f)
        binding.desc.text = item.description.html
        binding.ratingText.isVisible = item.scoreFlag != 1
        binding.chaptersValue.text = String.format(
            itemView.context.getString(R.string.xxx_chapters),
            item.chapterCount.toString()
        )

        val data = item.tabName ?: listOf()
        tags.forEachIndexed { index, view ->
            view.isVisible = index < data.size
            if (index < data.size) {
                view.tag = data[index]
                view.text = data[index]
            }
        }
    }
}